/*
 * Copyright(c)2018,2024,guowenmeng24@163.comAllrightsreserved.
 */
package com.bkhech.netty.nacos;

import cn.hutool.setting.dialect.Props;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingService;
import com.bkhech.netty.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * NacosClient
 *@author guowm
 *@date 2024/12/18
 */
@Slf4j
public class NacosClient {

    private static volatile NamingService namingService;

    private static NamingService initNamingService() {
        final Props properties = PropertiesUtil.getInstance();

        properties.setProperty(PropertyKeyConst.NAMESPACE, properties.getProperty("nacos.namespace"));
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, properties.getProperty("nacos.serverAddr"));
        properties.setProperty(PropertyKeyConst.USERNAME, properties.getProperty("nacos.username"));
        properties.setProperty(PropertyKeyConst.PASSWORD, properties.getProperty("nacos.password"));

        try {
            // 初始化配置中心的 Nacos Java SDK
            namingService = NacosFactory.createNamingService(properties);
        } catch (Exception e) {
            log.error("初始化 NamingService 失败：{},{}", e, e.getMessage());
            throw new RuntimeException(e);
        }
        return namingService;

    }

    public static NamingService getNamingService() {
        if (namingService == null) {
            synchronized (NacosClient.class) {
                if (namingService == null) {
                    namingService = initNamingService();
                }
            }
        }
        return namingService;
    }
}